package de.swm.gwt.client.authorization.impl;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.user.client.ui.UIObject;
import com.google.inject.Inject;

import de.swm.gwt.client.authorization.IAccessRight;
import de.swm.gwt.client.authorization.IDynamicAccessRight;
import de.swm.gwt.client.authorization.IRightsDependentUIUpdater;
import de.swm.gwt.client.authorization.IRoleConfiguration;
import de.swm.gwt.client.authorization.IUserRole;

/**
 * Aktualisierung von UI-Komponenten abhängig von ihren Rechten.
 *
 * @copyright 2013 SWM Services GmbH
 */
public class RightsDependentUiUpdater implements IRightsDependentUIUpdater {

	@Inject
	private IRoleConfiguration roleConfiguration;

	private Map<UIObject, IAccessRight> componentsToAccessRights = new HashMap<UIObject, IAccessRight>();
	private Map<UIObject, IDynamicAccessRight> componentsToDynamicAccessRights
		= new HashMap<UIObject, IDynamicAccessRight>();


	private void addExecutionRightRoles(IAccessRight executionRight, IUserRole... userRoles) {
		roleConfiguration.authorizeRolesForAccessRight(executionRight, userRoles);
	}

	/**
	 * Initialisiert die Rechte.
	 *
	 */
	public RightsDependentUiUpdater() {
	}


	@Override
	public void register(UIObject uiobject, IAccessRight accessRight) {
		componentsToAccessRights.put(uiobject, accessRight);
	}

	@Override
	public void register(UIObject uiobject, IAccessRight accessRight, IDynamicAccessRight authorizationCheck) {
		register(uiobject, accessRight);
		componentsToDynamicAccessRights.put(uiobject, authorizationCheck);
	}

	@Override
	public void updateComponents() {
		for (Map.Entry<UIObject, IAccessRight> e : componentsToAccessRights.entrySet()) {
			UIObject uiobject = e.getKey();

			IAccessRight executionRight = componentsToAccessRights.get(uiobject);
			if (executionRight == null) {
				throw new IllegalArgumentException("Kein Ausführungsrecht für das UiObject "
						+ uiobject.toString() + " konfiguriert.");
			}


			boolean staticCheck = roleConfiguration.isUserAuthorized(executionRight);


			IDynamicAccessRight authorizationCheck = componentsToDynamicAccessRights.get(uiobject);
			boolean dynamicCheck = authorizationCheck == null
					|| authorizationCheck.isAuthorized();
			if( uiobject.isVisible()){
				uiobject.setVisible(staticCheck && dynamicCheck);
			}
		}
	}

}
